const hre = require("hardhat");
const fs = require("fs");

async function main() {
  console.log("开始部署投票系统合约...");

  // 部署合约，设置投票持续时间为1小时(3600秒)
  const votingDuration = 3600;
  const VotingSystem = await hre.ethers.getContractFactory("VotingSystem");
  const votingSystem = await VotingSystem.deploy(votingDuration);

  await votingSystem.waitForDeployment();
  const votingSystemAddress = await votingSystem.getAddress();

  console.log(`投票系统合约已部署至地址: ${votingSystemAddress}`);

  // 等待区块确认后进行合约验证(如果不是本地网络)
  if (hre.network.name !== "hardhat" && hre.network.name !== "localhost") {
    console.log("等待区块确认...");
    // 等待6个区块确认
    await votingSystem.deployTransaction.wait(6);

    console.log("开始验证合约...");
    try {
      await hre.run("verify:verify", {
        address: votingSystem.address,
        constructorArguments: [votingDuration],
      });
      console.log("合约验证成功!");
    } catch (error) {
      console.error("合约验证失败:", error.message);
    }
  }

  // 将合约地址保存到前端目录供集成使用
  const contractAddressPath = "../frontend/src/contracts/contract-address.json";
  const contractABIPath = "../frontend/src/contracts/VotingSystemABI.json";

  // 创建目录(如果不存在)
  const fs = require("fs");
  const path = require("path");
  fs.mkdirSync(path.dirname(contractAddressPath), { recursive: true });

  // 保存合约地址
  fs.writeFileSync(
    contractAddressPath,
    JSON.stringify({ VotingSystem: votingSystemAddress }, null, 2)
  );

  // 保存合约ABI
  const abi = VotingSystem.interface.format('json');
  fs.writeFileSync(contractABIPath, abi);

  console.log("合约地址和ABI已保存至前端目录");
}

main().catch((error) => {
  console.error("部署过程中出错:", error);
  process.exitCode = 1;
});